package com.sojson.util.mail.interfaces.impl;

import java.io.IOException;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.aliyun.oss.ServiceException;
import com.sun.mail.util.MailSSLSocketFactory;

import lombok.extern.slf4j.Slf4j;

/**
 * 发送邮件工具类
 *
 * @author Liu
 *
 */
@Slf4j
@Component
public class MailSends {

    /**
     * 以异步的方式发送一封邮件
     *
     * @param target    目标邮箱
     * @param title     邮件标题
     * @param data      邮件内容
     * @throws Exception
     */
    @Async
    public void run(String target, String title, String data) throws Exception {
        Session session = createSession();

        // 发件人邮箱号码
        String mail = getUsername();

        try {
            // 创建邮件对象
            Message message = new MimeMessage(session);
            // 设置发件人
            message.setFrom(new InternetAddress(mail));
            // 设置接收人
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(target));
            // 设置邮件主题
            message.setSubject(title);
            // 设置邮件内容
            // String data = "<html><head></head><body><h1>你好，仓库的SN为:的物料已缺料，请尽快补料！需要补料，请尽快补料！</href></h3></body></html>";
            message.setContent(data, "text/html;charset=UTF-8");
            // 发送邮件
            Transport.send(message);
        } catch (MessagingException e) {
            StringBuffer str = new StringBuffer("");
            str.append("邮件发送失败！目标邮箱为:");
            str.append(target);
            str.append("。");
            str.append(e.getMessage());
            log.error(str.toString());
        }
    }

    /**
     * 以异步的方式发送一封邮件
     *
     * @param targets   目标邮箱
     * @param title     邮件标题
     * @param data      邮件内容
     * @throws Exception
     */
    @Async
    public void run(String[] targets, String title, String data) throws Exception {
        Session session = createSession();

        // 发件人邮箱号码
        String mail = getUsername();
        String target = null;

        int len = targets.length;
        for (int i = 0; i < len; i++) {
            target = targets[i];
            try {
                // 创建邮件对象
                Message message = new MimeMessage(session);
                // 设置发件人
                message.setFrom(new InternetAddress(mail));
                // 设置接收人
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(target));
                // 设置邮件主题
                message.setSubject(title);
                // 设置邮件内容
                // String data = "<html><head></head><body><h1>你好，仓库的SN为:的物料已缺料，请尽快补料！需要补料，请尽快补料！</href></h3></body></html>";
                message.setContent(data, "text/html;charset=UTF-8");
                // 发送邮件
                Transport.send(message);
            } catch (MessagingException e) {
                StringBuffer str = new StringBuffer("");
                str.append("第");
                str.append(i);
                str.append("封");
                str.append("邮件发送失败！目标邮箱为:");
                str.append(target);
                str.append("。");
                str.append(e.getMessage());
                log.error(str.toString());
            }
        }
    }

    /**
     * 创建Session对象
     *
     * @return
     * @throws Exception
     */
    private Session createSession() throws Exception {
        String host = null;
        String username = getUsername();
        String fromCode = getFromCode();
        if (username.endsWith("qq.com")) {
            host = "smtp.qq.com";
        } else if (username.endsWith("163.com")) {
            host = "smtp.163.com";
        } else {
            throw new ServiceException("此邮箱功能未实现");
        }
        return createSession(host, username, fromCode);
    }

    /**
     * 创建Session对象
     *
     * @param host      发送邮件的主机
     * @param username  发件人邮箱账号
     * @param fromCode  发件人邮箱授权码
     * @return
     * @throws Exception
     */
    private Session createSession(String host, String username, String fromCode) throws Exception {
        Properties properties = new Properties();// 获取系统属性

        if (host.equals("smtp.qq.com")) {
            // QQ邮箱需要下面这段代码
            MailSSLSocketFactory sf = null;
            sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", sf);
        }

        properties.setProperty("mail.smtp.host", host);// 设置邮件服务器
        properties.setProperty("mail.smtp.auth", "true");// 打开认证

        // 1.获取默认session对象
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, fromCode);// 发件人邮箱账号、授权码
            }
        });
        return session;
    }

    /**
     * 获取发件人邮箱账号
     *
     * @return
     * @throws IOException
     */
    private static String getUsername() throws IOException {
        return null;
    }

    /**
     * 获取发件人邮箱授权码
     *
     * @return
     * @throws IOException
     */
    private static String getFromCode() throws IOException {
        return null;
    }

    /**
     * 从缓存中获取值
     *
     * @param <T>
     * @param key
     * @return
     * @throws IOException
     */
    private static <T> T get(String key) throws IOException {
        return null;
    }

}